package com.taotao.search.service.impl;

import org.apache.solr.client.solrj.SolrQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.search.dao.SearchDao;
import com.taotao.search.pojo.SearchResult;
import com.taotao.search.service.SearchService;

@Service
public class SearchServiceImpl implements SearchService {

	@Autowired
	private SearchDao searchDao;

	/**
	 * 设置查询条件 设置分页条件 创建solrQuery对象 指定默认搜索域 高亮显示
	 */
	public SearchResult search(String queryString, int page, int rows) throws Exception {
		// 创建查询对象
		SolrQuery solrQuery = new SolrQuery();
		// 设置查询条件
		solrQuery.setQuery(queryString);
		// 分页
		solrQuery.setStart((page - 1) * rows);
		solrQuery.setRows(rows);
		// 默认搜索域
		solrQuery.set("df", "item_keywords");
		// 高亮显示
		solrQuery.setHighlight(true);
		solrQuery.addHighlightField("item_title");
		solrQuery.setHighlightSimplePre("<em style=\"color:red\">");
		solrQuery.setHighlightSimplePost("</em>");

		// 执行查询
		SearchResult searchResult = searchDao.search(solrQuery);
		// 计算总页数
		long recordCount = searchResult.getRecordCount();
		long pageCount = recordCount / rows;
		if (recordCount % rows > 0) {
			pageCount++;
		}
		// 设置（补全）查询结果
		searchResult.setPageCount(pageCount);
		searchResult.setCurPage(page);

		return searchResult;
	}

}
